/*
 * ipassbook 0.6.0
 * Copyright (C)2009 wateray and contributors
 * wateray@gmail.com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

package com.wateray.ipassbook.ui.dialog;

import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.MessageFormat;
import java.util.Vector;

import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

import org.apache.log4j.Logger;

import com.wateray.ipassbook.commom.Constant;
import com.wateray.ipassbook.domain.Subject;
import com.wateray.ipassbook.kernel.event.IPassbookEvent;
import com.wateray.ipassbook.kernel.event.IPassbookEventType;
import com.wateray.ipassbook.kernel.event.IPassbookObserver;
import com.wateray.ipassbook.kernel.service.SubjectService;
import com.wateray.ipassbook.ui.model.PassbookComboBoxModel;
import com.wateray.ipassbook.ui.model.SubjectListCellRender;
import com.wateray.ipassbook.ui.widget.TitleMessageDialog;
import com.wateray.ipassbook.util.LanguageLoader;
import com.wateray.ipassbook.util.log4j.Log;

/**
 * @author wateray
 * @create 2009-5-13
 */
public class AddSubjectDialog extends TitleMessageDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/** logger. */
	Logger logger = Log.getLogger(this.getClass());

	/** layout data. */
	private static int width = 380;
	private static int height = 320;
	private static int centerIndent = 25;

	/** type radioButton. */
	private JLabel typeLabel;
	private ButtonGroup incomeExpenseGroup;
	private JRadioButton incomeRadioButton;
	private JRadioButton expenseRadioButton;

	/** subject. */
	private JLabel subjectLabel;
	private JTextField subjectText;

	/** memo. */
	private JLabel memoLabel;
	private JTextField memoText;

	/** is child subject. */
	private JLabel isChildSubjectLabel;
	private JCheckBox isChildSubjectCheckBox;

	/** parent subject. */
	private JLabel parentSubjectLabel;
	private JComboBox parentSubjectComboBox;
	private PassbookComboBoxModel parentSubjectComboBoxModel;

	/** bottom button. */
	private JCheckBox continueCheckBox;

	/** data. */
	private String subjectId;

	public AddSubjectDialog(Component owner) {
		this(owner, width, height, true, LanguageLoader
				.getString("Add_Subject"));
	}

	public AddSubjectDialog(Component owner, String title) {
		this(owner, width, height, true, title);
	}

	public AddSubjectDialog(Component owner, int width, int height,
			boolean modal, String title) {
		super(owner, width, height, modal, title);
		// TODO Auto-generated constructor stub

		this.putButton(getContinueCheckBox());
		this.layoutButtonPanel();
	}

	@Override
	protected JComponent getCenterPane() {
		if (centerPane == null) {
			centerPane = new JPanel();
			GridBagLayout gridbag = new GridBagLayout();
			GridBagConstraints c = new GridBagConstraints();
			centerPane.setLayout(gridbag);
			// centerPane.setBorder(BorderFactory.createLineBorder(Color.red));

			int top = 5;
			int left = 15;
			int bottom = 15;
			int right = 15;
			Insets inserts = new Insets(top, left, 5, 5);
			/** type. */
			// typeLabel
			c.fill = GridBagConstraints.BOTH;
			c.weightx = 0.0;
			c.weighty = 0.0;
			c.insets = inserts;
			c.anchor = GridBagConstraints.SOUTHWEST;
			c.gridx = 0;
			c.gridy = 0;
			c.gridwidth = 1;
			c.gridheight = 1;
			gridbag.setConstraints(getTypeLabel(), c);
			centerPane.add(getTypeLabel());

			// incomeRadioButton
			c.gridx = 1;
			gridbag.setConstraints(getIncomeRadioButton(), c);
			centerPane.add(getIncomeRadioButton());

			// expenseRadioButton
			c.gridx = 2;
			gridbag.setConstraints(getExpenseRadioButton(), c);
			centerPane.add(getExpenseRadioButton());

			// incomeExpenseGroup
			incomeExpenseGroup = new ButtonGroup();
			incomeExpenseGroup.add(getIncomeRadioButton());
			incomeExpenseGroup.add(getExpenseRadioButton());

			// spaceLabel
			c.gridx = 3;
			c.weightx = 1.0;
			centerPane.add(new JLabel(), c);
			c.weightx = 0.0;

			/** subject. */
			// subjectLabel
			c.gridx = 0;
			c.gridy = 1;
			gridbag.setConstraints(getSubjectLabel(), c);
			centerPane.add(getSubjectLabel());

			// subjectText
			c.gridx = 1;
			c.gridwidth = 2;
			gridbag.setConstraints(getSubjectText(), c);
			centerPane.add(getSubjectText());

			/** memo. */
			// memoLabel
			c.gridx = 0;
			c.gridy = 2;
			gridbag.setConstraints(getMemoLabel(), c);
			centerPane.add(getMemoLabel());

			// memoText
			c.gridx = 1;
			c.gridwidth = 2;
			gridbag.setConstraints(getMemoText(), c);
			centerPane.add(getMemoText());

			c.insets = new Insets(centerIndent, left, 5, 5);
			/** isChilde. */
			// isChildSubjectLabel
			c.gridx = 0;
			c.gridy = 3;
			gridbag.setConstraints(getIsChildSubjectLabel(), c);
			centerPane.add(getIsChildSubjectLabel());

			// isChildSubjectCheckBox
			c.gridx = 1;
			c.gridwidth = 2;
			gridbag.setConstraints(getIsChildSubjectCheckBox(), c);
			centerPane.add(getIsChildSubjectCheckBox());

			c.insets = inserts;
			/** parent subject. */
			// parentSubjectLabel
			c.gridx = 0;
			c.gridy = 4;
			gridbag.setConstraints(getParentSubjectLabel(), c);
			centerPane.add(getParentSubjectLabel());

			// parentSubjectComboBox
			c.gridx = 1;
			c.gridwidth = 2;
			gridbag.setConstraints(getParentSubjectComboBox(), c);
			centerPane.add(getParentSubjectComboBox());

		}
		return centerPane;
	}

	@Override
	protected void initData() {
		getSubjectText().setText("");
		getMemoText().setText("");
		if(getIsChildSubjectCheckBox().isSelected()){
			getIsChildSubjectCheckBox().doClick();
		}
	}

	@Override
	protected void initState() {
		getSubjectText().requestFocus(true);

	}

	private void processData() {
		boolean flag = checkData();
		this.setMessageLabel(errorMessage);
		if (!flag) {
			return;
		}
		SubjectService service = new SubjectService();
		Subject entity = new Subject();
		entity
				.setSubjectFlag(getIncomeRadioButton().isSelected() ? Constant.INCOME_KBN
						: Constant.EXPENSE_KBN);
		entity.setName(getSubjectText().getText().trim());
		entity.setMemo(getMemoText().getText().trim());

		PassbookComboBoxModel subjectComboBoxModel = (PassbookComboBoxModel) getParentSubjectComboBox()
				.getModel();
		Subject parentSubject = (Subject) subjectComboBoxModel
				.getObjectAt(getParentSubjectComboBox().getSelectedIndex());
		if (getIsChildSubjectCheckBox().isSelected()) {
			entity.setParentId(parentSubject.getParentId());
		}

		int returnValue = service.insertSubject(entity);
		if (returnValue != 0) {
			// notify IPassbookEvent
			IPassbookObserver.getInstance().notifyEvents(
					new IPassbookEvent(this,
							IPassbookEventType.SubjectTableAddEvent));
		}

		// Finished.
		if (!continueCheckBox.isSelected()) {
			// Close this dialog.
			this.dispose();
		} else {
			// Continue to add record.
			initData();
		}

	}

	private boolean checkData() {
		errorMessage = "";

		// subjectText
		if (getSubjectText().getText().trim().equals("")) {
			errorMessage = MessageFormat.format(LanguageLoader
					.getString("empty"), getSubjectLabel().getText());
			getSubjectText().requestFocus();
			return false;
		}

		// is child subject
		PassbookComboBoxModel subjectComboBoxModel = (PassbookComboBoxModel) getParentSubjectComboBox()
				.getModel();
		Subject subject = (Subject) subjectComboBoxModel
				.getObjectAt(getParentSubjectComboBox().getSelectedIndex());
		if (getIsChildSubjectCheckBox().isSelected()) {
			if (subject == null) {
				errorMessage = MessageFormat.format(LanguageLoader
						.getString("empty"), getParentSubjectLabel().getText());
				getParentSubjectComboBox().requestFocus();
				return false;
			}

			// If is child,can not selected.
			if (subject.isChild()) {
				errorMessage = MessageFormat.format(LanguageLoader
						.getString("canNotSelected"),
						getParentSubjectComboBox().getSelectedItem());
				getParentSubjectComboBox().requestFocus();
				return false;
			}
		}

		return true;
	}

	public static void main(String[] args) {
		// Schedule a job for the event-dispatching thread:
		// creating and showing this application's GUI.
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				JFrame f = new JFrame("AddSubjectDialog");

				f.setContentPane(new AddSubjectDialog(null).getCenterPane());
				f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
				f.pack();
				f.setVisible(true);
			}
		});
	}

	/**
	 * @return the subjectId
	 */
	private String getSubjectId() {
		return subjectId;
	}

	/**
	 * @param subjectId
	 *            the subjectId to set
	 */
	private void setSubjectId(String subjectId) {
		this.subjectId = subjectId;
	}

	private JLabel getTypeLabel() {
		if (typeLabel == null) {
			typeLabel = new JLabel(LanguageLoader.getString("Receipt_Type"));
		}

		return typeLabel;
	}

	/**
	 * @return the incomeExpenseGroup
	 */
	private ButtonGroup getIncomeExpenseGroup() {
		if (incomeExpenseGroup == null) {
			incomeExpenseGroup = new ButtonGroup();
		}
		return incomeExpenseGroup;
	}

	/**
	 * @return the incomeRadioButton
	 */
	private JRadioButton getIncomeRadioButton() {
		if (incomeRadioButton == null) {
			incomeRadioButton = new JRadioButton(LanguageLoader
					.getString("Income"));
			incomeRadioButton.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent event) {
					HandleActionPerformed(event);
				}
			});
			incomeRadioButton.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent e) {
					HandleMouseClicked(e);
				}
			});

		}
		return incomeRadioButton;
	}

	/**
	 * @return the expenseRadioButton
	 */
	private JRadioButton getExpenseRadioButton() {
		if (expenseRadioButton == null) {
			expenseRadioButton = new JRadioButton(LanguageLoader
					.getString("Expense"));
			expenseRadioButton.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent event) {
					HandleActionPerformed(event);
				}
			});
			expenseRadioButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent event) {
					HandleActionPerformed(event);
				}
			});
			expenseRadioButton.doClick();
		}
		return expenseRadioButton;
	}

	/**
	 * @return the subjectLabel
	 */
	private JLabel getSubjectLabel() {
		if (subjectLabel == null) {
			subjectLabel = new JLabel(LanguageLoader.getString("SubjectEntity"));
		}
		return subjectLabel;
	}

	/**
	 * @return the subjectText
	 */
	private JTextField getSubjectText() {
		if (subjectText == null) {
			subjectText = new JTextField();
		}
		return subjectText;
	}

	/**
	 * @return the memoLabel
	 */
	private JLabel getMemoLabel() {
		if (memoLabel == null) {
			memoLabel = new JLabel(LanguageLoader.getString("Memo"));
		}
		return memoLabel;
	}

	/**
	 * @return the memoText
	 */
	private JTextField getMemoText() {
		if (memoText == null) {
			memoText = new JTextField();
		}
		return memoText;
	}

	/**
	 * @return the isChildSubjectLabel
	 */
	private JLabel getIsChildSubjectLabel() {
		if (isChildSubjectLabel == null) {
			isChildSubjectLabel = new JLabel(LanguageLoader.getString("Child?"));
		}
		return isChildSubjectLabel;
	}

	/**
	 * @return the isChildSubjectCheckBox
	 */
	private JCheckBox getIsChildSubjectCheckBox() {
		if (isChildSubjectCheckBox == null) {
			isChildSubjectCheckBox = new JCheckBox(LanguageLoader
					.getString("Yes"));
			isChildSubjectCheckBox.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					getParentSubjectComboBox().setEnabled(
							isChildSubjectCheckBox.isSelected());
					getParentSubjectComboBox().setSelectedIndex(-1);
				}
			});
		}
		return isChildSubjectCheckBox;
	}

	/**
	 * @return the parentSubjectLabel
	 */
	private JLabel getParentSubjectLabel() {
		if (parentSubjectLabel == null) {
			parentSubjectLabel = new JLabel(LanguageLoader.getString("Parent"));
		}
		return parentSubjectLabel;
	}

	/**
	 * @return the parentSubjectComboBox
	 */
	private JComboBox getParentSubjectComboBox() {
		if (parentSubjectComboBox == null) {
			parentSubjectComboBox = new JComboBox();
			parentSubjectComboBox.setEnabled(false);
			// parentSubjectComboBox.setMinimumSize(new Dimension(160, 0));
			// parentSubjectComboBox.setPreferredSize(new Dimension(160, 0));
			parentSubjectComboBox.setModel(getParentSubjectComboBoxModel());
			parentSubjectComboBox.setRenderer(new SubjectListCellRender());
		}

		return parentSubjectComboBox;
	}

	/**
	 * @return the parentSubjectComboBoxModel
	 */
	private PassbookComboBoxModel getParentSubjectComboBoxModel() {
		if (parentSubjectComboBoxModel == null) {
			parentSubjectComboBoxModel = new PassbookComboBoxModel();
		}
		return parentSubjectComboBoxModel;
	}

	/**
	 * @return the continueCheckBox
	 */
	private JCheckBox getContinueCheckBox() {
		if (continueCheckBox == null) {
			continueCheckBox = new JCheckBox(LanguageLoader
					.getString("Continue_Add"));
			// continueCheckBox.doClick();
		}
		return continueCheckBox;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seecom.wateray.ipassbook.ui.dialog.TitleMessageDialog#
	 * finishButtonActionPerformed(java.awt.event.ActionEvent)
	 */
	@Override
	protected void finishButtonActionPerformed(ActionEvent event) {
		// TODO Auto-generated method stub
		processData();
	}

	private void HandleActionPerformed(ActionEvent event) {
		Handler(event.getSource());

	}

	private void HandleMouseClicked(MouseEvent event) {
		Handler(event.getSource());
	}

	private void Handler(Object source) {
		if (source.equals(incomeRadioButton)) {
			Vector<Subject> dataVector = new SubjectService()
					.getParentAndChildrenListByFlag(Constant.INCOME_KBN);
			getParentSubjectComboBoxModel().setData(dataVector);
		} else if (source.equals(expenseRadioButton)) {
			Vector<Subject> dataVector = new SubjectService()
					.getParentAndChildrenListByFlag(Constant.EXPENSE_KBN);
			getParentSubjectComboBoxModel().setData(dataVector);
		}
	}

	@Override
	public void update(IPassbookEvent event) {
		// TODO Auto-generated method stub

	}

}
